package com.jmlee.controller;

import com.jmlee.component.HostHolder;
import com.jmlee.pojo.*;
import com.jmlee.pojo.AShop;
import com.jmlee.service.AdminService;
import com.jmlee.service.ShopService;
import com.jmlee.util.JSONUtil;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 商家管理
 *
 * @author xl W
 * @date 2021/3/13 15:58
 */

@Controller
public class ShopController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private ShopService shopService;
    @Autowired
    private AdminService adminService;

    @Value("${default.path.upload}")
    private String uploadPath;

    @Value("${default.path.domain}")
    private String domain;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    //================================商家管理=========================================================

    /**
     * 添加后台商家
     *
     * @param
     * @param request
     * @return
     */


    @RequestMapping("shopCount")
    @ResponseBody
    public PageBean<AShop> count(AShop shop, HttpServletRequest request, HttpServletResponse response) throws IOException {


        int curPage = Integer.valueOf(request.getParameter("page"));
        int pageSize = Integer.valueOf(request.getParameter("limit"));


        RowBounds rowBounds = new RowBounds((curPage - 1) * pageSize, pageSize);
        PageBean<AShop> pageBean = new PageBean<>();

        pageBean.setCode(0);
        int count = shopService.selectShopListCount(shop);

        pageBean.setCount(count);
        pageBean.setData(shopService.selectShopList(shop, rowBounds));

//
//        String json = JSONUtil.objectToJson(pageBean);
//        System.out.println("json:"+json);
        return pageBean;
    }

    /**
     * 商家查询
     * @param name
     * @param model
     * @return
     */
//    @RequestMapping("/turnletter")
//    public String updateUser(String name, Model model){
//        //根据用户的id查询用户信息
//        Shop shop=adminService.queryShopById(name);
//        model.addAttribute("shop",shop);
//        System.out.println(shop);
//        return "letter";
//    }
    /**
     * 商家删除
     *
     * @author xl W
     * @date 2021/3/5 15:55
     */
    @RequestMapping("adminDelete")
    @ResponseBody
    public String adminDelete(@RequestBody AShop shop, HttpServletRequest request) {
//        String aId = request.getParameter("aId");
//        System.out.println("嗯" + shop.toString());
        boolean s = shopService.shopDelete(shop);
        if (s == true) {
//            request.getSession().setAttribute("shop",s);
            return "修改成功";
        }
        return "修改失败";
    }

    //跳转商家管理页面
    @RequestMapping("turnShop")
    public String turnShop() {
//        System.out.println("来过了");
        return "shop";
    }

    //用户审核通过
    @RequestMapping("shopCan")
    @ResponseBody
    public String shopCan(String aId, HttpServletRequest request) throws IOException {
//        System.out.println("要展示了");
        System.out.println(aId);
        boolean s = shopService.shuoCan(aId);
        if (s == true) {
            return "更新成功";
        }
        return "更新失败";
    }
    //用户审核不通过
    @RequestMapping("shopNoPass")
    @ResponseBody
    public String shopNoPass(String aId, HttpServletRequest request) throws IOException {
//        System.out.println("要展示了");
//        System.out.println(aId);
        boolean s = shopService.shopNoPass(aId);
        if (s == true) {
            return "更新成功";
        }
        return "更新失败";
    }


    //禁用
    @RequestMapping("shopForbidden")
    @ResponseBody
    public String shopForbidden(@RequestBody AShop shop, HttpServletRequest request) throws IOException {
//        System.out.println("嗯" + shop.toString());
        boolean s = shopService.shopForbidden(shop);
        if (s == true) {
            return "禁用成功";
        }

        return "禁用失败";
    }

    //启用
    @RequestMapping("shopStart")
    @ResponseBody
    public String shopStart(@RequestBody AShop shop, HttpServletRequest request) throws IOException {
//        System.out.println("嗯" + shop.toString());
        boolean s = shopService.shopStart(shop);
        if (s == true) {
            return "启用成功";
        }

        return "启用失败";
    }

    //    =========================================查看商铺信息========================================================

    @GetMapping("/shopInfo")
    public ModelAndView checkShop() {
        Admin admin = hostHolder.getAdmin();
        ModelAndView modelAndView = new ModelAndView("shopInfo");
        AShop shop = shopService.queryShopById(admin.getId());
        modelAndView.addObject("shop", shop);
//        System.out.println(shop);
        modelAndView.addObject("admin", admin);


        return modelAndView;
    }

    /**
     * 上传营业资格证
     * @param licenseImg
     * @return
     */
    @PostMapping("uploadLicense")
    @ResponseBody
    public CommonResult uploadLicense(@RequestParam(value = "file") MultipartFile licenseImg){
        String format = sdf.format(new Date());
        String filePath = "";
        File folder = new File(uploadPath + format);
        if (!folder.exists()) {
            if (folder.isDirectory()) {
                folder.mkdirs();
            }
        }
        // 对上传的文件重命名，避免文件重名
        String oldName = licenseImg.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            licenseImg.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
             filePath = "http://47.99.200.116/" + format + "/" + newName;

        }catch (IOException e){
            return CommonResult.failed("网络异常");
        }
        return CommonResult.success(filePath,"success");
    }

    /**
     * 修改店铺信息
     * @param shopMap
     * @return
     */
    @PostMapping("editShopInfo")
    @ResponseBody
    public CommonResult editShopInfo(@RequestBody Map<String, Object> shopMap){
        String status = "";
//        System.out.println(shopMap.get("username"));
        String shopJson = JSONUtil.objectToJson(shopMap.get("shop"));
        AShop aShop = JSONUtil.jsonToPojo(shopJson,AShop.class);
//        System.out.println(shopMap.get("shop").toString());
        Admin admin = new Admin();
        admin.setId(aShop.getaId());
        admin.setUsername((String) shopMap.get("username"));
        status = adminService.updateAdminSubmit(admin).toString();
        status = shopService.editShopInfo(aShop).toString();

        return CommonResult.success(status,"success");
    }
}
